package com.github.hwangrq.myrpc.consumer.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;


@ChannelHandler.Sharable
public class RpcClientHandler extends SimpleChannelInboundHandler<String>
        implements Callable<Object> {

    /** 事件处理器上下文对象 (存储handler信息,写操作) */
    private ChannelHandlerContext context;

    /** 客户端发送消息 */
    private String requestMsg;

    /** 服务端消息 */
    private String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    /**
     * 通道连接就绪事件
     * 实现channelActive  客户端和服务器连接时,该方法就自动执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
        //初始化ChannelHandlerContext
        context = ctx;
    }

    /**
     * 通道读取就绪事件
     * 实现channelRead 当我们读到服务器数据,该方法自动执行
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        responseMsg = msg;
        //唤醒等待的线程
        notify();
    }

    /**
     * 发送消息到服务端（将客户端的数据写到服务器）
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {
        //消息发送
        context.writeAndFlush(requestMsg);
        //线程等待
        wait();
        return responseMsg;
    }
}
